package top.lyc829.iot_android.fragment.profile.finger;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.SPUtils;
import com.gturedi.views.StatefulLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.widget.actionbar.TitleBar;

import java.util.List;

import butterknife.BindView;
import top.lyc829.iot_android.R;
import top.lyc829.iot_android.adapter.FingerAdapter;
import top.lyc829.iot_android.adapter.FriendAdapter;
import top.lyc829.iot_android.core.BaseFragment;
import top.lyc829.iot_android.entity.Finger;
import top.lyc829.iot_android.entity.User;
import top.lyc829.iot_android.http.service.UserService;
import top.lyc829.iot_android.http.subscriber.NoTipRequestSubscriber;

@Page(name = "FingerFragment")
public class FingerFragment extends BaseFragment {

    @BindView(R.id.finger_recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_stateful)
    StatefulLayout mLlStateful;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private FingerAdapter adapter;

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setTitle("指纹");
        titleBar.addAction(new TitleBar.TextAction("添加指纹") {
            @Override
            public void performAction(View view) {
                addFinger();
            }
        });
        return titleBar;
    }


    public static FingerFragment newInstance() {
        return new FingerFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.finger_fragment;
    }

    @Override
    protected void initViews() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(adapter = new FingerAdapter());
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void initListeners() {
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final @NonNull RefreshLayout refreshLayout) {
                mLlStateful.showLoading();
                getFingerList(refreshLayout);
            }
        });
        mRefreshLayout.autoRefresh();

        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Bundle params = new Bundle();
            params.putInt("position", position);
            params.putSerializable("finger", adapter.getItem(position));
            openPageForResult(EditFingerFragment.class, params, 1234);
        });

    }

    private void getFingerList(RefreshLayout refreshLayout) {

        CustomRequest request = XHttp.custom();

        request.apiCall(request.create(UserService.class).getFingers(Integer.parseInt(SPUtils.getInstance().getString("token", "-1"))))
                .subscribeWith(new NoTipRequestSubscriber<List<Finger>>() {
                    @Override
                    protected void onSuccess(List<Finger> fingers) {
                        if (fingers == null || fingers.size() == 0) {
                            mLlStateful.showEmpty();
                        } else {
                            mLlStateful.showContent();
                        }
                        refreshLayout.finishRefresh(true);
                        adapter.setList(fingers);
                    }

                    @Override
                    public void onError(ApiException e) {
                        refreshLayout.finishRefresh(true);
                        mLlStateful.showError(e.getMessage(), v -> {
                            getFingerList(refreshLayout);
                        });
                    }
                });

    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (data != null && requestCode == 1234) {
            int position = data.getIntExtra("position", -1);
            String name = data.getStringExtra("name");
            if (position >= 0 && position < adapter.getData().size()) {
                if (data.getBooleanExtra("isDelete", false)) {
                    adapter.removeAt(position);
                } else {
                    adapter.getItem(position).setFingerName(name);
                    adapter.notifyItemChanged(position);
                }
            }
        }
    }


    private void addFinger() {
        Bundle params = new Bundle();
        params.putBoolean("isAdd", true);
        openPage(EditFingerFragment.class, params);
    }
}